<template>
  <div class="search-box">
    <a-modal
      v-model:open="open"
      width="850px"
      :title="`${!!searchForm.id ? '编辑' : '新建'}实体属性`"
      :confirmLoading="loading"
      @cancel="hideModal"
      @ok="handleOk"
    >
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="属性名称" v-bind="validateInfos.field">
          <a-input
            :disabled="!!searchForm.id"
            v-model:value="searchForm.field"
            placeholder="请输入属性名称"
          />
        </a-form-item>
        <a-form-item label="属性显称" v-bind="validateInfos.name">
          <a-input v-model:value="searchForm.name" placeholder="请输入属性显称" />
        </a-form-item>
        <a-form-item label="数据类型" v-bind="validateInfos.type">
          <a-select
            cle
            :disabled="!!searchForm.id"
            v-model:value="searchForm.type"
            placeholder="请选择数据类型"
          >
            <a-select-option v-for="(code, lable) in propertyType" :key="code" :value="code">{{
              lable
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="字典" v-bind="validateInfos.dictType">
          <a-select
            allowClear
            :disabled="!!searchForm.id"
            v-model:value="searchForm.dictType"
            placeholder="请选择字典"
          >
            <a-select-option v-for="item in dictTypeList" :key="item.id" :value="item.code">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="示例/说明" v-bind="validateInfos.remark">
          <a-textarea v-model:value="searchForm.remark" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import {
  apiGetDictTypeList,
  apiUpdateMetaEntity,
  apiUpdateMetaEntityProperty
} from '@/services/tableDemo'
import { propertyType } from '@/utils/constant'
import message from 'ant-design-vue/es/message'

const emit = defineEmits<(e: 'reload', type?: number) => void>()
const open = ref<boolean>(false)
const loading = ref<boolean>(false)

const labelCol = { style: { width: '150px' } }
const wrapperCol = { span: 14 }
const searchForm = reactive<TABLE_PARAMS.EntityProperty>({
  id: undefined,
  field: '',
  name: '',
  type: undefined,
  dictType: undefined,
  remark: undefined
})
// 字典类型列表
const dictTypeList = ref<TABLE_PARAMS.DictType[]>([])

const rulesRef = reactive({
  field: [
    {
      required: true,
      message: '请输入属性名称'
    },
    { pattern: /^\w{1,32}$/, message: '请输入1-32位字母和数字' }
  ],
  name: [
    {
      required: true,
      message: '请输入属性显称'
    },
    { pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{1,128}$/, message: '请输入1-128位属性显称' }
  ],
  type: [
    {
      required: true,
      message: '请选择数据类型'
    }
  ],
  remark: [
    {
      pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{0,128}$/,
      message: '只允许输入汉字、字母、数字和下划线，长度在128个字符之内'
    }
  ]
})

const { resetFields, validate, validateInfos } = Form.useForm(searchForm, rulesRef, {})

// 打开弹窗
const showModal = (info?: TABLE_PARAMS.EntityProperty) => {
  if (info) {
    Object.assign(searchForm, info)
  }
  open.value = true
}
// 关闭弹窗
const hideModal = () => {
  // 清空和恢复默认
  resetFields()
  open.value = false
  loading.value = false
}

// 更新元数据
const updateMetaEntity = async () => {
  return await apiUpdateMetaEntity({
    id: searchForm.entityId,
    properties: [toRaw(searchForm)]
  })
}

// 更新元数据属性
const updateMetaEntityProperty = () => {
  return apiUpdateMetaEntityProperty({ ...toRaw(searchForm) })
}

// 提交
const handleOk = () => {
  validate().then(async () => {
    loading.value = true
    let res
    if (searchForm.id) {
      res = await updateMetaEntityProperty()
    } else {
      res = await updateMetaEntity()
    }
    if (res?.responseCode === 100000000) {
      message.success('操作成功')
      hideModal()
      emit('reload')
    } else {
      message.warning(res && res.responseMessage)
    }
    loading.value = false
  })
}

// 获取字典类型列表
const getDictTypeList = async () => {
  const res = await apiGetDictTypeList({ pageNumber: 1, pageSize: 99999 })
  const { datas } = res.data
  dictTypeList.value = datas || []
}

onMounted(() => {
  getDictTypeList()
})

defineExpose({
  showModal
})
</script>
<style lang="less" scoped>
.add-entity {
  position: absolute;
  right: -100px;
}
</style>
